import common from "./common";
import constants from "./constants";
import utils from "../utils/utils";
import { message } from '@common/assets/js/resetMessage';

const procArraybuffer = arraybuffer => {
	return new Promise(resolve => {
		let blob = new Blob([ arraybuffer ], {
			type: 'application/json',
		});
		const reader = new FileReader();
		reader.onload = e => {
			const res1 = e.target.result
			try {
				const json = JSON.parse(res1);
				if (json.code === 1000) {
					utils.logout();
					location.hash = '/login';
				} else {
					if (utils.isNotEmpty(json.message) && json.message.startsWith('{') && json.message.endsWith('}')) {
						let msgJson = JSON.parse(json.message);
						resolve(msgJson);
					} else {
						resolve(json)
					}
				}
			} catch (err) {
				resolve();
			}
		};
		reader.readAsText(blob);
	});
}
const downloadExcelFile = (arraybuffer, output_name, with_date = false) => {
	let dateName = utils.formatDate(new Date(), 'yyyy-MM-dd');
	output_name = output_name.replace(/\.xlsx/g, '');
	output_name = output_name.replace(/\.xls/g, '');
	let fileName = `${ output_name }${ with_date ? '_' + dateName : '' }.xlsx`;
	let blob = new Blob([ arraybuffer ], {
		type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8'
	});
	if (window.navigator.msSaveOrOpenBlob) {
		navigator.msSaveBlob(blob, fileName);
	} else {
		let link = document.createElement('a');
		link.href = window.URL.createObjectURL(blob);
		link.download = fileName;
		link.click();
		window.URL.revokeObjectURL(link.href);
	}
};
const poiApi = {
	getFullUrl: url => {
		return window.configs.requestPrefix + url;
	},
	getDownloadUrl: fileName => {
		return `${ window.configs.requestPrefix }/template/${ fileName }`;
	},
	exportExcel: (title_field, url, params, output_name, convert, pageNo, pageSize, with_date) => {
		let subData = {
			title_field: JSON.stringify(title_field),
			url: poiApi.getFullUrl(url),
			params,
			output_name,
			convert,
			pageNo,
			pageSize,
		};
		if (!utils.isNotEmpty(title_field)) {
			message.error('模板定义不能为空');
			return;
		}
		if (!utils.isNotEmpty(url)) {
			message.error('请求路径不能为空');
			return;
		}
		if (!utils.isNotEmpty(params)) {
			message.error('请求参数不能为空');
			return;
		}
		if (!utils.isNotEmpty(output_name)) {
			message.error('文件名称不能为空');
			return;
		}
		common.exportData(constants.API_ExportExcel, subData, {
			responseType: 'arraybuffer',
			timeout: 10 * 60 * 1000,
		}, res => {
			procArraybuffer(res).then(json => {
				if (json) {
					if (json.code !== 0) {
						message.error(json.message);
					}
				} else {
					downloadExcelFile(res, output_name, with_date);
				}
			});
		});
	},
	exportExcelNew: ({ title_field, url, params, output_name, convert, pageNo, pageSize, with_date, save_file = false, data }) => {
		if (!utils.isNotEmpty(title_field)) {
			message.error('模板定义不能为空');
			return;
		}
		if (!utils.isNotEmpty(url)) {
			message.error('请求路径不能为空');
			return;
		}
		if (!utils.isNotEmpty(params)) {
			message.error('请求参数不能为空');
			return;
		}
		if (!utils.isNotEmpty(output_name)) {
			message.error('文件名称不能为空');
			return;
		}
		if (!params) {
			params = {};
		}
		if (!utils.isNotEmpty(params.dr)) {
			params.dr = 0;
		}
		let subData = {
			title_field: JSON.stringify(title_field),
			url: poiApi.getFullUrl(url),
			params,
			output_name,
			convert,
			pageNo,
			pageSize,
			save_file: save_file ? 1 : 0,
		};
		if (data) {
			subData.data = JSON.stringify(data);
		}
		common.exportData(constants.API_ExportExcel, subData, {
			responseType: 'arraybuffer',
			timeout: 10 * 60 * 1000,
		}, res => {
			procArraybuffer(res).then(json => {
				if (json) {
					if (json.code !== 0) {
						message.error(json.message);
					}
				} else {
					downloadExcelFile(res, output_name, with_date);
				}
			});
		});
	},
	exportExcelTemplate: (template_name, url, params, output_name, convert, pic_field, pageNo, pageSize, save_file, with_date,
                          merged_cell_with_border) => {
		if (!params) {
			params = {};
		}
		if (!utils.isNotEmpty(params.dr)) {
			params.dr = 0;
		}
		let subData = {
			template_name,
			url: poiApi.getFullUrl(url),
			params,
			output_name,
			convert: typeof convert === 'undefined' ? {} : convert,
			pic_field,
			pageNo,
			pageSize,
			save_file: save_file ? 1 : 0,
            merged_cell_with_border,
		};
		if (!utils.isNotEmpty(template_name)) {
			message.error('模板名称不能为空');
			return;
		}
		if (!utils.isNotEmpty(url)) {
			message.error('请求路径不能为空');
			return;
		}
		if (!utils.isNotEmpty(params)) {
			message.error('请求参数不能为空');
			return;
		}
		if (!utils.isNotEmpty(output_name)) {
			message.error('文件名称不能为空');
			return;
		}
		return new Promise((resolve, reject) => {
			common.exportData(constants.API_ExportExcelTemplate, subData, {
				responseType: 'arraybuffer'
			}, res => {
				procArraybuffer(res).then(result => {
					if (save_file) {
						let resData = result.data || {};
						resolve(resData);
					} else {
						if (result) {
							if (result.code !== 0) {
								message.error(result.message);
								reject();
							}
						} else {
							resolve();
							downloadExcelFile(res, output_name, with_date);
						}
					}
				});
			}, err => {
				reject(err);
			});
		});
	},
	exportExcelTemplateNew: ({
		                         template_name,
		                         url,
		                         params,
		                         output_name,
		                         convert = {},
		                         pic_field,
		                         pageNo,
		                         pageSize,
		                         save_file = false,
		                         with_date,
		                         data,
                                 merged_cell_with_border,
                                 auto_height = true,
	                         }) => {
		if (!params) {
			params = {};
		}
		if (!utils.isNotEmpty(params.dr)) {
			params.dr = 0;
		}
		let subData = {
			template_name,
			url: poiApi.getFullUrl(url),
			params,
			output_name,
			convert,
			pic_field,
			pageNo,
			pageSize,
			save_file: save_file ? 1 : 0,
            merged_cell_with_border,
            auto_height: auto_height ? '1' : '0',
		};
		if (data) {
			subData.data = JSON.stringify(data);
		}
		if (!utils.isNotEmpty(template_name)) {
			message.error('模板名称不能为空');
			return;
		}
		if (!utils.isNotEmpty(url)) {
			message.error('请求路径不能为空');
			return;
		}
		if (!utils.isNotEmpty(params)) {
			message.error('请求参数不能为空');
			return;
		}
		if (!utils.isNotEmpty(output_name)) {
			message.error('文件名称不能为空');
			return;
		}
		return new Promise((resolve, reject) => {
			common.exportData(constants.API_ExportExcelTemplate, subData, {
				responseType: 'arraybuffer'
			}, res => {
				procArraybuffer(res).then(result => {
					if (save_file) {
						let resData = result.data || {};
						resolve(resData);
					} else {
						if (result) {
							if (result.code !== 0) {
								message.error(result.message);
								reject();
							}
						} else {
							resolve();
							downloadExcelFile(res, output_name, with_date);
						}
					}
				});
			}, err => {
				reject(err);
			});
		});
	},
	exportExcelTemplateCustom: (template_name, url, params, output_name, save_file, with_date, col_foreach) => {
		let subData = {
			template_name,
			url: poiApi.getFullUrl(url),
			params,
			output_name,
			custom: '1',
			save_file: save_file ? 1 : 0,
			col_foreach: col_foreach ? '1' : undefined,
		};
		if (!utils.isNotEmpty(template_name)) {
			message.error('模板名称不能为空');
			return;
		}
		if (!utils.isNotEmpty(url)) {
			message.error('请求路径不能为空');
			return;
		}
		if (!utils.isNotEmpty(params)) {
			message.error('请求参数不能为空');
			return;
		}
		if (!utils.isNotEmpty(output_name)) {
			message.error('文件名称不能为空');
			return;
		}
		return new Promise(resolve => {
			common.exportData(constants.API_ExportExcelTemplate, subData, {
				responseType: 'arraybuffer'
			}, res => {
				procArraybuffer(res).then(result => {
					if (save_file) {
						let resData = result.data || {};
						resolve(resData);
					} else {
						if (result) {
							if (result.code !== 0) {
								message.error(result.message);
							}
						} else {
							downloadExcelFile(res, output_name, with_date);
						}
					}
				});
			});
		});
	},
    exportExcelTemplateMultiSheet: (template_name, sheets, output_name, convert = {}, pic_field, pageNo, pageSize, save_file = false, with_date,merged_cell_with_border) => {
        let subData = {
            template_name,
            sheets,
            output_name,
            convert,
            pic_field,
            pageNo,
            pageSize,
            save_file: save_file ? 1 : 0,
            merged_cell_with_border,
        };
        if (!utils.isNotEmpty(template_name)) {
            message.error('模板名称不能为空');
            return;
        }
        if (!utils.isNotEmpty(sheets)) {
            message.error('多页配置不能为空');
            return;
        }
        if (!utils.isNotEmpty(output_name)) {
            message.error('文件名称不能为空');
            return;
        }
        return new Promise(resolve => {
            common.exportData(constants.API_ExportExcelTemplateMultiSheet, subData, {
                responseType: 'arraybuffer'
            }, res => {
                procArraybuffer(res).then(result => {
                    if (save_file) {
                        let resData = result.data || {};
                        resolve(resData);
                    } else {
                        downloadExcelFile(res, output_name, with_date);
                    }
                });
            });
        });
    },
	exportExcelTemplateCustomNew: ({
		                               template_name,
		                               url,
		                               params,
		                               output_name,
		                               save_file = false,
		                               with_date,
		                               col_foreach = false,
	                               }) => {
		let subData = {
			template_name,
			url: poiApi.getFullUrl(url),
			params,
			output_name,
			custom: '1',
			save_file: save_file ? 1 : 0,
			col_foreach: col_foreach ? '1' : undefined,
		};
		if (!utils.isNotEmpty(template_name)) {
			message.error('模板名称不能为空');
			return;
		}
		if (!utils.isNotEmpty(url)) {
			message.error('请求路径不能为空');
			return;
		}
		if (!utils.isNotEmpty(params)) {
			message.error('请求参数不能为空');
			return;
		}
		if (!utils.isNotEmpty(output_name)) {
			message.error('文件名称不能为空');
			return;
		}
		return new Promise(resolve => {
			common.exportData(constants.API_ExportExcelTemplate, subData, {
				responseType: 'arraybuffer'
			}, res => {
				procArraybuffer(res).then(result => {
					if (save_file) {
						let resData = result.data || {};
						resolve(resData);
					} else {
						if (result) {
							if (result.code !== 0) {
								message.error(result.message);
							}
						} else {
							downloadExcelFile(res, output_name, with_date);
						}
					}
				});
			});
		});
	},
	readExcel: (file_id, config_file, last_row_skip_qty) => {
		if (!utils.isNotEmpty(file_id)) {
			message.error('Excel文件不能为空');
			return;
		}
		if (!utils.isNotEmpty(config_file)) {
			message.error('Excel配置文件不能为空');
			return;
		}
		return new Promise((resolve, reject) => {
			let subData = { file_id, config_file, last_row_skip_qty, timeout: 10 * 60 * 1000 };
			common.requestData(constants.API_ReadExcel, subData, result => {
				resolve(result);
			}, err => {
				if (err.code === 2000) {
					typeof reject === 'function' && reject(err);
				} else {
					message.error(err.message);
				}
			});
		});
	},
};
export default poiApi;
